package com.ruoyi.project.system.user.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.ilabUtils.IlabUtil;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.util.token.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;

import java.net.URLEncoder;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private IlabUtil ilabUtil;

    @Autowired
    private IUserService userService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        if (request.getParameter("imPSLogin") != null) {
            return "Tslogin";
        }
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @PostMapping("/Tslogin")
    @ResponseBody
    public AjaxResult Tslogin() {
        String username = "评审账户";
        String password = "Ps*15441";
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }


    /**
     * 通过ilab解析ticket内容信息
     *
     * @param data
     * @return
     */
    @CrossOrigin
    @PostMapping("/ilab/auth")
    @ResponseBody
    public AjaxResult ilabAuth(@RequestBody String data) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String ticket = jsonObject.getString("ticket");
            /**
             * 调用ilab接口获取用户信息
             */
            String ilabJson = ilabUtil.getAccessToken(ticket);
            JSONObject o = JSONObject.parseObject(ilabJson);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if (code != 0) {
                return AjaxResult.error(o.getString("msg"));
            } else {
                return AjaxResult.success(o);
            }
        } catch (Exception e) {
            return AjaxResult.error("token解析失败，请稍后重新通过ilab进入重做实验");
        }
    }

    /**
     * ilab解析数据成功登录,否则就系统登录
     *
     * @param data
     * @return
     */
    @PostMapping("/ilab/login")
    @ResponseBody
    public AjaxResult ilabLogin(@RequestBody String data) {
        try {
            JSONObject o = JSONObject.parseObject(data);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if (code != 0) {
                return AjaxResult.error("token失效，请重新通过ilab进入重做实验");
            }
            String loginName = o.getString("un");
            String username = o.getString("dis");
            //如果数据库存在登陆用户名 则直接返回
            User user = userService.selectUserByLoginName(loginName);
            if (user != null) {
                user.setUserName(username);
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                Long[] roleIds = {4L};
                user.setRoleIds(roleIds);
                userService.updateUser2(user);
                UsernamePasswordToken token1 = new UsernamePasswordToken(loginName, "Ilab123456");
                Subject subject = SecurityUtils.getSubject();
                subject.login(token1);
                return success();
            } else {
                //不存在则在用户数据表中创建用户数据
                User userVo = new User();
                userVo.setLoginName(loginName);
                userVo.setUserName(username);
                String phoneNum = randomNumber();
                userVo.setPhonenumber(phoneNum);
                userVo.setPassword("Ilab123456");
                userVo.setEmail(phoneNum + "@ilab.com");
                userVo.setStatus("0");
                userVo.setSex("0");
                Long[] roleIds = {4L};
                //学生身份
                userVo.setRoleIds(roleIds);
                userVo.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                int resultCount = userService.insertUser2(userVo);
            }
            UsernamePasswordToken token1 = new UsernamePasswordToken(loginName, "Ilab123456");
            Subject subject = SecurityUtils.getSubject();
            subject.login(token1);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }


    public static String randomNumber() {
        String[] start = {"133", "149", "153", "173", "177",
                "180", "181", "189", "199", "130", "131", "132",
                "145", "155", "156", "166", "171", "175", "176", "185", "186", "166", "134", "135",
                "136", "137", "138", "139", "147", "150", "151", "152", "157", "158", "159", "172",
                "178", "182", "183", "184", "187", "188", "198", "170", "171"};
        //随机出真实号段   使用数组的length属性，获得数组长度，
        //通过Math.random（）*数组长度获得数组下标，从而随机出前三位的号段
        String phoneFirstNum = start[(int) (Math.random() * start.length)];
        //随机出剩下的8位数
        String phoneLastNum = "";
        //定义尾号，尾号是8位
        final int LENPHONE = 8;
        //循环剩下的位数
        for (int i = 0; i < LENPHONE; i++) {
            //每次循环都从0~9挑选一个随机数
            phoneLastNum += (int) (Math.random() * 10);
        }
        //最终将号段和尾数连接起来
        String phoneNum = phoneFirstNum + phoneLastNum;
        return phoneNum;
    }
}
